<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>五子棋精品版</title>
    <style>
        :root {
            --primary-color: #8B4513;
            --board-color: #E8C192;
            --highlight-color: #F0D4A8;
            --shadow-color: rgba(0, 0, 0, 0.25);
        }
        
        body {
            font-family: 'Arial', sans-serif;
            display: flex;
            justify-content: center;
            align-items: center;
            height: 100vh;
            margin: 0;
            background: linear-gradient(135deg, #f5f7fa 0%, #c3cfe2 100%);
            overflow: hidden;
        }
        .container {
            display: flex;
            flex-direction: column;
            align-items: center;
            max-width: 800px;
            width: 100%;
            padding: 10px;
            box-sizing: border-box;
        }
        .game-area {
            display: flex;
            flex-direction: column;
            align-items: center;
            width: 100%;
        }
        canvas {
            display: block;
            box-shadow: 0 8px 24px rgba(0,0,0,0.1);
            border-radius: 5px;
            margin-bottom: 15px;
        }
        h1 {
            color: #333;
            text-align: center;
            margin-bottom: 20px;
            text-shadow: 1px 1px 3px rgba(0,0,0,0.1);
        }
        .status {
            font-size: 1.2em;
            margin: 10px 0;
            padding: 8px 15px;
            background: rgba(255,255,255,0.8);
            border-radius: 20px;
            box-shadow: 0 2px 10px rgba(0,0,0,0.05);
            width: 100%;
            text-align: center;
            transition: all 0.3s ease;
        }
        .controls {
            display: flex;
            justify-content: center;
            flex-wrap: wrap;
            gap: 10px;
            margin-top: 10px;
            margin-bottom: 15px;
            width: 100%;
        }
        button {
            padding: 10px 20px;
            font-size: 1em;
            background: linear-gradient(to bottom, #6a11cb 0%, #2575fc 100%);
            color: white;
            border: none;
            border-radius: 20px;
            cursor: pointer;
            transition: all 0.3s ease;
            box-shadow: 0 4px 10px rgba(0,0,0,0.1);
            min-width: 100px;
        }
        button:hover {
            transform: translateY(-2px);
            box-shadow: 0 6px 15px rgba(0,0,0,0.15);
        }
        button:active {
            transform: translateY(1px);
            box-shadow: 0 2px 5px rgba(0,0,0,0.1);
        }
        button:disabled {
            background: #cccccc;
            cursor: not-allowed;
        }
        .black-turn {
            background-color: #333;
            color: white;
        }
        .white-turn {
            background-color: #f5f5f5;
            color: #333;
            border: 1px solid #ddd;
        }
        
        /* 完全确保Undo按钮可见 */
        @media (max-height: 800px) {
            .container {
                padding-bottom: 60px;
            }
            body {
                overflow-y: auto;
            }
        }
        
        /* 响应式布局 */
        @media (max-width: 600px) {
            .container {
                padding: 5px;
            }
            h1 {
                font-size: 1.5em;
            }
            .status {
                font-size: 1em;
            }
            button {
                padding: 8px 15px;
                font-size: 0.9em;
            }
        }
    </style>
</head>
<body>
    <div class="container">
        <h1>五子棋精品版</h1>
        <div class="game-area">
            <div class="canvas-container">
                <canvas id="gameCanvas" width="450" height="450" tabindex="0" aria-label="五子棋棋盘" role="application"></canvas>
                <div id="currentPositionMarker"></div>
            </div>
            <div class="controls">
                <button id="undoButton" onclick="undoMove()" aria-label="悔棋">悔棋</button>
                <button id="saveButton" onclick="saveGame()" aria-label="保存游戏">保存游戏</button>
                <button id="loadButton" onclick="loadGame()" aria-label="读取游戏">读取游戏</button>
            </div>
        </div>
        <div class="status" id="gameInfo">当前轮到黑棋</div>
    </div>
    
    <div id="gameOverDialog" class="game-over-dialog" role="dialog" aria-modal="true" aria-labelledby="gameOverMessage">
        <p id="gameOverMessage"></p>
        <button onclick="resetGame()" aria-label="重新开始游戏">重新开始</button>
    </div>
    
    <div id="moveHistory" class="history-container" style="display: none;">
        <h3>棋局记录</h3>
        <div id="moveList"></div>
    </div>
    
    <audio id="moveSound" preload="auto">
        <source src="data:audio/mpeg;base64,SUQzBAAAAAABEVRYWFgAAAAtAAADY29tbWVudABCaWdTb3VuZEJhbmsuY29tIC8gTGFTb25vdGhlcXVlLm9yZwBURU5DAAAAHQAAA1N3aXRjaCBQbHVzIMKpIE5DSCBTb2Z0d2FyZQBUSVQyAAAABgAAAzIyMzUAVFNTRQAAAA8AAANMYXZmNTcuODMuMTAwAAAAAAAAAAAAAAD/80DEAAAAA0gAAAAATEFNRTMuMTAwVVVVVVVVVVVVVUxBTUUzLjEwMFVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVf/zQsRbAAADSAAAAABVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVf/zQMSkAAADSAAAAABVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVV" type="audio/mpeg">
    </audio>
    <audio id="winSound" preload="auto">
        <source src="data:audio/mpeg;base64,SUQzBAAAAAABEVRYWFgAAAAtAAADY29tbWVudABCaWdTb3VuZEJhbmsuY29tIC8gTGFTb25vdGhlcXVlLm9yZwBURU5DAAAAHQAAA1N3aXRjaCBQbHVzIMKpIE5DSCBTb2Z0d2FyZQBUSVQyAAAABgAAAzIyMzUAVFNTRQAAAA8AAANMYXZmNTcuODMuMTAwAAAAAAAAAAAAAAD/80DEAAAAA0gAAAAATEFNRTMuMTAwVVVVVVVVVVVVVUxBTUUzLjEwMFVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVf/zQsRbAAADSAAAAABVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVf/zQMSkAAADSAAAAABVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVV" type="audio/mpeg">
    </audio>
    <script>
        // 获取DOM元素
        const canvas = document.getElementById('gameCanvas');
        const ctx = canvas.getContext('2d');
        const gameInfo = document.getElementById('gameInfo');
        const gameOverDialog = document.getElementById('gameOverDialog');
        const gameOverMessage = document.getElementById('gameOverMessage');
        const moveSound = document.getElementById('moveSound');
        const winSound = document.getElementById('winSound');
        const positionMarker = document.getElementById('currentPositionMarker');
        const moveList = document.getElementById('moveList');
        
        // 游戏常量
        const GRID_SIZE = 15;
        let CELL_SIZE = canvas.width / GRID_SIZE;
        let BOARD_SIZE = canvas.width;
        
        // 游戏状态变量
        let board = Array.from({ length: GRID_SIZE }, () => Array(GRID_SIZE).fill(0));
        let currentPlayer = 1; // 1: 黑棋, -1: 白棋
        let gameOver = false;
        let moveHistory = []; // 记录每一步的落子位置
        let currentPosition = { x: -1, y: -1 }; // 当前光标位置
        let lastMoveTime = 0; // 用于动画效果
        let frames = 0; // 帧计数器，用于性能监控
        let startTime = performance.now();
        
        // 渲染相关变量
        let animationFrameId = null;
        let particles = []; // 特效粒子
        
        // 游戏变量
        let canvas, ctx;
        let BOARD_SIZE = 400; // 棋盘大小
        const GRID_SIZE = 20; // 网格数量
        let CELL_SIZE = BOARD_SIZE / GRID_SIZE; // 单元格大小

        // 蛇的变量
        let snake = []; // 蛇的身体，每个部分是一个坐标 {x, y}
        let direction = 'right'; // 初始方向
        let nextDirection = 'right'; // 下一个方向（防止在同一帧内多次改变方向）
        let food = null; // 食物的位置 {x, y}
        let gameRunning = false; // 游戏状态
        let score = 0; // 分数
        let gameSpeed = 150; // 游戏速度（毫秒）
        let gameInterval; // 游戏定时器
        let particles = []; // 粒子效果

        // 颜色定义
        const colors = {
            board: '#f0f0f0',
            gridLines: '#e0e0e0',
            snake: {
                head: '#4CAF50',
                body: '#8BC34A',
                outline: '#2E7D32'
            },
            food: '#FF5722',
            gameOver: 'rgba(255, 0, 0, 0.3)'
        };

        // 初始化函数
        function init() {
            // 重置游戏状态
            board = [];
            for (let i = 0; i < GRID_SIZE; i++) {
                board.push(new Array(GRID_SIZE).fill(0));
            }
            moveHistory = [];
            particles = [];
            gameOver = false;
            currentPlayer = 1; // 黑棋先行
            
            // 重置UI状态
            updateStatusMessage();
            
            // 设置画布大小并调整布局
            resizeCanvas();
            
            // 添加事件监听器（确保只添加一次）
            canvas.removeEventListener('click', handleCanvasClick);
            canvas.addEventListener('click', handleCanvasClick);
            
            window.removeEventListener('resize', resizeCanvas);
            window.addEventListener('resize', resizeCanvas);
            
            // 绘制棋盘
            drawBoard();
            
            // 启动游戏循环
            startGameLoop();
        }
        
        // 调整画布大小
        function resizeCanvas() {
            // 获取可用空间
            const container = document.querySelector('.game-area');
            const availableWidth = container.clientWidth;
            const availableHeight = window.innerHeight * 0.8; // 使用80%的窗口高度
            
            // 确定画布大小（取较小值，确保正方形）
            const size = Math.min(availableWidth, availableHeight);
            BOARD_SIZE = size;
            CELL_SIZE = BOARD_SIZE / GRID_SIZE;
            
            // 设置画布尺寸
            canvas.width = BOARD_SIZE;
            canvas.height = BOARD_SIZE;
            
            // 重新绘制
            drawBoard();
            drawAllPieces();
            
            console.log(`Canvas resized: ${BOARD_SIZE}x${BOARD_SIZE}, Cell: ${CELL_SIZE}`);
        }
        
        // 游戏主循环
        function startGameLoop() {
            if (animationFrameId) {
                cancelAnimationFrame(animationFrameId);
            }
            
            function gameLoop(timestamp) {
                // 更新帧率计数
                frames++;
                if (timestamp - startTime >= 1000) {
                    // 每秒更新一次FPS
                    const fps = Math.round(frames * 1000 / (timestamp - startTime));
                    console.log(`FPS: ${fps}`);
                    frames = 0;
                    startTime = timestamp;
                }
                
                // 清除画布
                ctx.clearRect(0, 0, canvas.width, canvas.height);
                
                // 绘制基本棋盘
                drawBoard();
                
                // 绘制所有棋子
                drawAllPieces();
                
                // 绘制最后落子标记
                if (moveHistory.length > 0) {
                    const lastMove = moveHistory[moveHistory.length - 1];
                    drawLastMoveMarker(lastMove.x, lastMove.y);
                }
                
                // 更新并绘制粒子效果
                updateParticles();
                drawParticles();
                
                // 继续循环
                animationFrameId = requestAnimationFrame(gameLoop);
            }
            
            animationFrameId = requestAnimationFrame(gameLoop);
        }
        
        // 绘制棋盘
        function drawBoard() {
            console.log("绘制棋盘, 大小:", BOARD_SIZE, "单元格大小:", CELL_SIZE);
            
            // 清除整个画布
            ctx.clearRect(0, 0, canvas.width, canvas.height);
            
            // 绘制棋盘背景
            const gradient = ctx.createRadialGradient(
                BOARD_SIZE/2, BOARD_SIZE/2, BOARD_SIZE/10,
                BOARD_SIZE/2, BOARD_SIZE/2, BOARD_SIZE/1.5
            );
            gradient.addColorStop(0, '#F0D4A8');
            gradient.addColorStop(1, '#E8C192');
            
            ctx.fillStyle = gradient;
            ctx.fillRect(0, 0, BOARD_SIZE, BOARD_SIZE);
            
            // 添加木纹效果
            const woodGrain = 30;
            for (let i = 0; i < BOARD_SIZE; i += woodGrain) {
                ctx.beginPath();
                ctx.strokeStyle = 'rgba(139, 69, 19, 0.05)';
                ctx.lineWidth = woodGrain / 1.5;
                
                // 随机曲线模拟木纹
                ctx.moveTo(0, i + (Math.random() * woodGrain/2));
                
                for (let x = 0; x < BOARD_SIZE; x += BOARD_SIZE/10) {
                    const variance = Math.sin(x/50) * woodGrain/3;
                    ctx.lineTo(x, i + variance + (Math.random() * woodGrain/4));
                }
                
                ctx.stroke();
            }
            
            // 绘制外边框
            ctx.lineWidth = 2;
            ctx.strokeStyle = '#9E6B4A';
            ctx.strokeRect(CELL_SIZE/2, CELL_SIZE/2, BOARD_SIZE - CELL_SIZE, BOARD_SIZE - CELL_SIZE);
            
            // 绘制网格线
            ctx.lineWidth = 1;
            
            for (let i = 0; i < GRID_SIZE; i++) {
                // 绘制水平线
                ctx.beginPath();
                ctx.moveTo(CELL_SIZE/2, i * CELL_SIZE + CELL_SIZE/2);
                ctx.lineTo(BOARD_SIZE - CELL_SIZE/2, i * CELL_SIZE + CELL_SIZE/2);
                ctx.strokeStyle = '#9E6B4A';
                ctx.stroke();
                
                // 绘制垂直线
                ctx.beginPath();
                ctx.moveTo(i * CELL_SIZE + CELL_SIZE/2, CELL_SIZE/2);
                ctx.lineTo(i * CELL_SIZE + CELL_SIZE/2, BOARD_SIZE - CELL_SIZE/2);
                ctx.strokeStyle = '#9E6B4A';
                ctx.stroke();
            }
            
            // 绘制天元和星位
            const starPoints = [
                {x: 3, y: 3}, {x: 11, y: 3}, {x: 3, y: 11}, {x: 11, y: 11}, {x: 7, y: 7},
                {x: 3, y: 7}, {x: 11, y: 7}, {x: 7, y: 3}, {x: 7, y: 11}
            ];
            
            starPoints.forEach(point => {
                ctx.beginPath();
                ctx.arc(
                    point.x * CELL_SIZE + CELL_SIZE/2,
                    point.y * CELL_SIZE + CELL_SIZE/2,
                    4, 0, Math.PI * 2
                );
                ctx.fillStyle = '#8B4513';
                ctx.fill();
            });
        }
        
        // 绘制所有棋子
        function drawAllPieces() {
            // 检查是否存在有效的棋盘数据
            if (!board || board.length === 0) {
                console.error("棋盘数据不存在");
                return;
            }
            
            // 遍历棋盘绘制所有棋子
            for (let y = 0; y < GRID_SIZE; y++) {
                for (let x = 0; x < GRID_SIZE; x++) {
                    if (board[y][x] !== 0) {
                        drawPiece(x, y, board[y][x]);
                    }
                }
            }
        }
        
        // 绘制单个棋子
        function drawPiece(x, y, player) {
            const centerX = x * CELL_SIZE + CELL_SIZE/2;
            const centerY = y * CELL_SIZE + CELL_SIZE/2;
            const radius = CELL_SIZE/2 - 3;
            
            // 绘制阴影
            ctx.beginPath();
            ctx.arc(centerX + 2, centerY + 2, radius, 0, 2 * Math.PI);
            ctx.fillStyle = 'rgba(0, 0, 0, 0.2)';
            ctx.fill();
            
            // 棋子底部边缘（增加立体感）
            ctx.beginPath();
            ctx.arc(centerX, centerY, radius + 1, 0, 2 * Math.PI);
            ctx.fillStyle = player === 1 ? '#444' : '#ddd';
            ctx.fill();
            
            // 主体棋子
            ctx.beginPath();
            ctx.arc(centerX, centerY, radius, 0, 2 * Math.PI);
            
            // 创建渐变效果
            const gradient = ctx.createRadialGradient(
                centerX - radius/3, centerY - radius/3, radius/8,
                centerX, centerY, radius
            );
            
            if (player === 1) { // 黑棋
                gradient.addColorStop(0, '#666');
                gradient.addColorStop(0.5, '#333');
                gradient.addColorStop(1, '#000');
            } else { // 白棋
                gradient.addColorStop(0, '#fff');
                gradient.addColorStop(0.5, '#f5f5f5');
                gradient.addColorStop(1, '#e0e0e0');
            }
            
            ctx.fillStyle = gradient;
            ctx.fill();
            
            // 棋子边缘（增加精细度）
            ctx.beginPath();
            ctx.arc(centerX, centerY, radius, 0, 2 * Math.PI);
            ctx.strokeStyle = player === 1 ? '#000' : '#bbb';
            ctx.lineWidth = 1;
            ctx.stroke();
            
            // 高光效果（更加自然）
            ctx.beginPath();
            // 创建一个椭圆形的高光
            const highlightRadius = radius * 0.35;
            const highlightX = centerX - radius * 0.3;
            const highlightY = centerY - radius * 0.3;
            
            ctx.ellipse(
                highlightX, 
                highlightY, 
                highlightRadius * 0.7, 
                highlightRadius, 
                Math.PI / 4, 
                0, 2 * Math.PI
            );
            
            const highlightGradient = ctx.createRadialGradient(
                highlightX, highlightY, 0,
                highlightX, highlightY, highlightRadius
            );
            
            if (player === 1) { // 黑棋高光
                highlightGradient.addColorStop(0, 'rgba(255, 255, 255, 0.3)');
                highlightGradient.addColorStop(1, 'rgba(0, 0, 0, 0)');
            } else { // 白棋高光
                highlightGradient.addColorStop(0, 'rgba(255, 255, 255, 0.9)');
                highlightGradient.addColorStop(1, 'rgba(255, 255, 255, 0.2)');
            }
            
            ctx.fillStyle = highlightGradient;
            ctx.fill();
        }

        function checkWin(x, y, player) {
            const directions = [
                [1, 0], // 水平
                [0, 1], // 垂直
                [1, 1], // 正对角线
                [1, -1] // 反对角线
            ];

            for (let [dx, dy] of directions) {
                let count = 1;
                for (let i = 1; i < 5; i++) {
                    const nx = x + dx * i;
                    const ny = y + dy * i;
                    if (nx >= 0 && nx < GRID_SIZE && ny >= 0 && ny < GRID_SIZE && board[nx][ny] === player) {
                        count++;
                    } else {
                        break;
                    }
                }
                for (let i = 1; i < 5; i++) {
                    const nx = x - dx * i;
                    const ny = y - dy * i;
                    if (nx >= 0 && nx < GRID_SIZE && ny >= 0 && ny < GRID_SIZE && board[nx][ny] === player) {
                        count++;
                    } else {
                        break;
                    }
                }
                if (count >= 5) {
                    return true;
                }
            }
            return false;
        }

        function checkDraw() {
            return board.every(row => row.every(cell => cell !== 0));
        }

        function handleCanvasClick(event) {
            if (gameOver) return;
            
            const rect = canvas.getBoundingClientRect();
            const scaleX = canvas.width / rect.width;
            const scaleY = canvas.height / rect.height;
            
            const x = Math.floor(((event.clientX - rect.left) * scaleX) / CELL_SIZE);
            const y = Math.floor(((event.clientY - rect.top) * scaleY) / CELL_SIZE);
            
            placePiece(x, y);
        }

        function resetGame() {
            board = Array.from({ length: GRID_SIZE }, () => Array(GRID_SIZE).fill(0));
            currentPlayer = 1;
            gameOver = false;
            moveHistory = [];
            gameInfo.textContent = '当前轮到黑棋';
            gameOverDialog.style.display = 'none';
            drawBoard();
        }

        function undoMove() {
            if (moveHistory.length === 0 || gameOver) return;

            const lastMove = moveHistory.pop();
            board[lastMove.x][lastMove.y] = 0;
            currentPlayer = lastMove.player;

            // 重绘棋盘
            drawBoard();
            moveHistory.forEach(move => drawPiece(move.x, move.y, move.player));

            gameInfo.textContent = currentPlayer === 1 ? '当前轮到黑棋' : '当前轮到白棋';
        }

        canvas.addEventListener('click', handleCanvasClick);
        window.addEventListener('keydown', (event) => {
            if (event.key === 'r' && gameOver) {
                resetGame();
            }
        });

        // 保存游戏
        function saveGame() {
            if (gameOver) return;
            
            const gameData = {
                board: board,
                currentPlayer: currentPlayer,
                moveHistory: moveHistory
            };
            
            try {
                localStorage.setItem('gomokuGame', JSON.stringify(gameData));
                
                // 显示保存成功提示
                const savedMessage = document.createElement('div');
                savedMessage.textContent = '游戏已保存';
                savedMessage.style.position = 'fixed';
                savedMessage.style.top = '20px';
                savedMessage.style.left = '50%';
                savedMessage.style.transform = 'translateX(-50%)';
                savedMessage.style.backgroundColor = 'rgba(0, 128, 0, 0.8)';
                savedMessage.style.color = 'white';
                savedMessage.style.padding = '10px 20px';
                savedMessage.style.borderRadius = '5px';
                savedMessage.style.zIndex = '1000';
                
                document.body.appendChild(savedMessage);
                
                setTimeout(() => {
                    document.body.removeChild(savedMessage);
                }, 2000);
            } catch (e) {
                console.error('保存游戏失败:', e);
            }
        }
        
        // 加载游戏
        function loadGame() {
            try {
                const gameData = JSON.parse(localStorage.getItem('gomokuGame'));
                
                if (!gameData) {
                    const noSaveMessage = document.createElement('div');
                    noSaveMessage.textContent = '没有找到保存的游戏';
                    noSaveMessage.style.position = 'fixed';
                    noSaveMessage.style.top = '20px';
                    noSaveMessage.style.left = '50%';
                    noSaveMessage.style.transform = 'translateX(-50%)';
                    noSaveMessage.style.backgroundColor = 'rgba(255, 0, 0, 0.8)';
                    noSaveMessage.style.color = 'white';
                    noSaveMessage.style.padding = '10px 20px';
                    noSaveMessage.style.borderRadius = '5px';
                    noSaveMessage.style.zIndex = '1000';
                    
                    document.body.appendChild(noSaveMessage);
                    
                    setTimeout(() => {
                        document.body.removeChild(noSaveMessage);
                    }, 2000);
                    
                    return;
                }
                
                board = gameData.board;
                currentPlayer = gameData.currentPlayer;
                moveHistory = gameData.moveHistory;
                gameOver = false;
                gameInfo.textContent = currentPlayer === 1 ? '当前轮到黑棋' : '当前轮到白棋';
                gameOverDialog.style.display = 'none';
                
                // 更新历史记录显示
                updateMoveHistory();
                
                // 显示加载成功提示
                const loadedMessage = document.createElement('div');
                loadedMessage.textContent = '游戏已加载';
                loadedMessage.style.position = 'fixed';
                loadedMessage.style.top = '20px';
                loadedMessage.style.left = '50%';
                loadedMessage.style.transform = 'translateX(-50%)';
                loadedMessage.style.backgroundColor = 'rgba(0, 128, 0, 0.8)';
                loadedMessage.style.color = 'white';
                loadedMessage.style.padding = '10px 20px';
                loadedMessage.style.borderRadius = '5px';
                loadedMessage.style.zIndex = '1000';
                
                document.body.appendChild(loadedMessage);
                
                setTimeout(() => {
                    document.body.removeChild(loadedMessage);
                }, 2000);
            } catch (e) {
                console.error('加载游戏失败:', e);
            }
        }
        
        // 检查是否有保存的游戏
        function checkSavedGame() {
            if (localStorage.getItem('gomokuGame')) {
                const loadButton = document.getElementById('loadButton');
                if (loadButton) {
                    loadButton.disabled = false;
                }
            }
        }
        
        // 粒子效果 - 创建粒子
        function generateParticles(x, y, player) {
            const particleCount = 20;
            const color = player === 1 ? '#000' : '#fff';
            
            for (let i = 0; i < particleCount; i++) {
                particles.push({
                    x: x,
                    y: y,
                    size: Math.random() * 4 + 1,
                    speedX: (Math.random() - 0.5) * 8,
                    speedY: (Math.random() - 0.5) * 8,
                    color: color,
                    alpha: 1,
                    rotation: Math.random() * 360,
                    life: 30 + Math.random() * 20
                });
            }
        }
        
        // 更新粒子状态
        function updateParticles() {
            for (let i = particles.length - 1; i >= 0; i--) {
                const p = particles[i];
                
                // 处理不同类型的粒子
                if (p.isRing) {
                    // 光环粒子
                    p.alpha -= 0.015;
                    if (p.expand) {
                        p.size *= 1.06;
                    }
                } else if (p.spiral) {
                    // 螺旋粒子
                    p.x += p.speedX;
                    p.y += p.speedY;
                    p.spiralRadius *= p.spiralExpand;
                    p.x += Math.cos(p.spiralAngle) * p.spiralRadius * 0.1;
                    p.y += Math.sin(p.spiralAngle) * p.spiralRadius * 0.1;
                    p.spiralAngle += 0.2;
                    p.alpha -= 0.01;
                } else {
                    // 普通粒子
                    p.x += p.speedX;
                    p.y += p.speedY;
                    if (p.gravity) {
                        p.speedY += p.gravity;
                    }
                    p.alpha -= 0.015;
                }
                
                p.life -= 1;
                
                // 移除消失的粒子
                if (p.alpha <= 0 || p.life <= 0) {
                    particles.splice(i, 1);
                }
            }
        }
        
        // 绘制粒子
        function drawParticles() {
            particles.forEach(p => {
                ctx.save();
                ctx.globalAlpha = p.alpha;
                
                if (p.isRing) {
                    // 绘制光环
                    ctx.beginPath();
                    ctx.arc(p.x, p.y, p.size, 0, Math.PI * 2);
                    ctx.lineWidth = 3;
                    ctx.strokeStyle = p.color;
                    ctx.stroke();
                } else if (p.isShadow) {
                    // 绘制阴影
                    ctx.beginPath();
                    ctx.arc(p.x, p.y, p.size, 0, Math.PI * 2);
                    ctx.fillStyle = p.color;
                    ctx.fill();
                } else if (p.isBounce) {
                    // 绘制弹跳效果
                    ctx.beginPath();
                    ctx.arc(p.x, p.y, p.size, 0, Math.PI * 2);
                    
                    const gradient = ctx.createRadialGradient(
                        p.x - p.size/3, p.y - p.size/3, p.size/10,
                        p.x, p.y, p.size
                    );
                    
                    if (p.color === '#000') { // 黑棋
                        gradient.addColorStop(0, '#666');
                        gradient.addColorStop(0.5, '#333');
                        gradient.addColorStop(1, '#000');
                    } else { // 白棋
                        gradient.addColorStop(0, '#fff');
                        gradient.addColorStop(0.5, '#f5f5f5');
                        gradient.addColorStop(1, '#e0e0e0');
                    }
                    
                    ctx.fillStyle = gradient;
                    ctx.fill();
                    
                    // 添加高光
                    ctx.beginPath();
                    ctx.arc(
                        p.x - p.size * 0.3,
                        p.y - p.size * 0.3,
                        p.size * 0.25,
                        0, Math.PI * 2
                    );
                    ctx.fillStyle = p.color === '#000' ? 'rgba(255,255,255,0.2)' : 'rgba(255,255,255,0.8)';
                    ctx.fill();
                } else if (p.spiral) {
                    // 星形粒子
                    ctx.fillStyle = p.color;
                    ctx.translate(p.x, p.y);
                    ctx.rotate(p.rotation * Math.PI / 180);
                    
                    const spikes = 5;
                    const outerRadius = p.size;
                    const innerRadius = p.size / 2;
                    
                    ctx.beginPath();
                    for (let i = 0; i < spikes * 2; i++) {
                        const radius = i % 2 === 0 ? outerRadius : innerRadius;
                        const angle = (Math.PI / spikes) * i;
                        
                        if (i === 0) {
                            ctx.moveTo(radius, 0);
                        } else {
                            ctx.lineTo(
                                Math.cos(angle) * radius,
                                Math.sin(angle) * radius
                            );
                        }
                    }
                    ctx.closePath();
                    ctx.fill();
                } else {
                    // 方形粒子
                    ctx.fillStyle = p.color;
                    ctx.translate(p.x, p.y);
                    ctx.rotate(p.rotation * Math.PI / 180);
                    ctx.fillRect(-p.size / 2, -p.size / 2, p.size, p.size);
                }
                
                ctx.restore();
            });
        }
        
        // 创建胜利特效
        function createVictoryEffect(x, y) {
            const centerX = x * CELL_SIZE + CELL_SIZE/2;
            const centerY = y * CELL_SIZE + CELL_SIZE/2;
            
            // 创建更多粒子
            for (let i = 0; i < 100; i++) {
                const angle = Math.random() * Math.PI * 2;
                const distance = Math.random() * 150 + 50;
                const speed = 1 + Math.random() * 3;
                
                particles.push({
                    x: centerX,
                    y: centerY,
                    size: Math.random() * 6 + 2,
                    speedX: Math.cos(angle) * speed,
                    speedY: Math.sin(angle) * speed,
                    color: `hsl(${Math.random() * 360}, 100%, 50%)`,
                    alpha: 1,
                    rotation: Math.random() * 360,
                    life: 60 + Math.random() * 40,
                    gravity: 0.05 * Math.random()
                });
            }
            
            // 创建光环效果
            for (let i = 0; i < 8; i++) {
                setTimeout(() => {
                    particles.push({
                        x: centerX,
                        y: centerY,
                        size: 80 + i * 30,
                        isRing: true,
                        color: `hsl(${i * 30}, 100%, 60%)`,
                        alpha: 0.7,
                        life: 40,
                        expand: true
                    });
                }, i * 120);
            }
            
            // 创建螺旋效果
            for (let i = 0; i < 5; i++) {
                const spiralCount = 20;
                const angleOffset = (Math.PI * 2) / spiralCount;
                
                setTimeout(() => {
                    for (let j = 0; j < spiralCount; j++) {
                        const angle = j * angleOffset;
                        const speed = 2 + i * 0.5;
                        
                        particles.push({
                            x: centerX,
                            y: centerY,
                            size: 4 + Math.random() * 4,
                            speedX: Math.cos(angle) * speed,
                            speedY: Math.sin(angle) * speed,
                            color: `hsl(${(j * 360 / spiralCount + i * 30) % 360}, 100%, 60%)`,
                            alpha: 1,
                            life: 50 + Math.random() * 20,
                            spiral: true,
                            spiralAngle: angle,
                            spiralRadius: 10,
                            spiralExpand: 1.1
                        });
                    }
                }, i * 300);
            }
        }
        
        // 绘制棋盘实时阴影效果
        function drawBoardShadow() {
            // 绘制棋盘阴影效果，随着时间变化
            const time = performance.now() / 1000;
            const shadowOffset = Math.sin(time) * 5 + 10;
            
            ctx.shadowColor = 'rgba(0, 0, 0, 0.3)';
            ctx.shadowBlur = shadowOffset;
            ctx.shadowOffsetX = shadowOffset;
            ctx.shadowOffsetY = shadowOffset;
            
            // 绘制完成后重置阴影
            ctx.shadowColor = 'transparent';
            ctx.shadowBlur = 0;
            ctx.shadowOffsetX = 0;
            ctx.shadowOffsetY = 0;
        }
        
        // 绘制最后落子标记
        function drawLastMoveMarker(x, y) {
            const centerX = x * CELL_SIZE + CELL_SIZE/2;
            const centerY = y * CELL_SIZE + CELL_SIZE/2;
            
            // 绘制外圈
            ctx.beginPath();
            ctx.arc(centerX, centerY, CELL_SIZE/4, 0, Math.PI * 2);
            ctx.strokeStyle = 'rgba(255, 0, 0, 0.7)';
            ctx.lineWidth = 2;
            ctx.stroke();
            
            // 绘制内圈
            ctx.beginPath();
            ctx.arc(centerX, centerY, CELL_SIZE/8, 0, Math.PI * 2);
            ctx.fillStyle = 'rgba(255, 0, 0, 0.4)';
            ctx.fill();
        }
        
        // 处理鼠标移动
        function handleMouseMove(event) {
            const rect = canvas.getBoundingClientRect();
            const scaleX = canvas.width / rect.width;
            const scaleY = canvas.height / rect.height;
            
            const x = Math.floor(((event.clientX - rect.left) * scaleX) / CELL_SIZE);
            const y = Math.floor(((event.clientY - rect.top) * scaleY) / CELL_SIZE);
            
            if (x >= 0 && x < GRID_SIZE && y >= 0 && y < GRID_SIZE) {
                const centerX = x * CELL_SIZE + CELL_SIZE/2;
                const centerY = y * CELL_SIZE + CELL_SIZE/2;
                
                positionMarker.style.display = 'block';
                positionMarker.style.left = `${centerX + canvas.offsetLeft}px`;
                positionMarker.style.top = `${centerY + canvas.offsetTop}px`;
                
                currentPosition = { x, y };
            } else {
                positionMarker.style.display = 'none';
            }
        }
        
        // 处理键盘输入
        function handleKeyPress(event) {
            if (gameOver) {
                if (event.key === 'r' || event.key === 'R') {
                    resetGame();
                    return;
                }
            }
            
            if (currentPosition.x === -1) {
                currentPosition = { x: Math.floor(GRID_SIZE/2), y: Math.floor(GRID_SIZE/2) };
            }
            
            switch(event.key) {
                case 'ArrowUp':
                case 'w':
                case 'W':
                    if (direction !== 'down') nextDirection = 'up';
                    break;
                case 'ArrowDown':
                case 's':
                case 'S':
                    if (direction !== 'up') nextDirection = 'down';
                    break;
                case 'ArrowLeft':
                case 'a':
                case 'A':
                    if (direction !== 'right') nextDirection = 'left';
                    break;
                case 'ArrowRight':
                case 'd':
                case 'D':
                    if (direction !== 'left') nextDirection = 'right';
                    break;
                case 'Enter':
                case ' ':
                    if (currentPosition.x !== -1 && !gameOver) {
                        placePiece(currentPosition.x, currentPosition.y);
                    }
                    event.preventDefault();
                    break;
                case 'z':
                case 'Z':
                    if (event.ctrlKey || event.metaKey) {
                        undoMove();
                        event.preventDefault();
                    }
                    break;
            }
            
            // 如果游戏未运行，且按下了方向键，自动开始游戏
            if (!gameRunning && ['ArrowUp', 'ArrowDown', 'ArrowLeft', 'ArrowRight', 'w', 'a', 's', 'd', 'W', 'A', 'S', 'D'].includes(event.key)) {
                startGame();
            }
        }
        
        // 更新位置标记
        function updatePositionMarker() {
            if (currentPosition.x !== -1) {
                const centerX = currentPosition.x * CELL_SIZE + CELL_SIZE/2;
                const centerY = currentPosition.y * CELL_SIZE + CELL_SIZE/2;
                
                positionMarker.style.display = 'block';
                positionMarker.style.left = `${centerX + canvas.offsetLeft}px`;
                positionMarker.style.top = `${centerY + canvas.offsetTop}px`;
            }
        }
        
        // 放置棋子
        function placePiece(x, y) {
            // 检查位置是否有效且没有棋子
            if (x < 0 || x >= GRID_SIZE || y < 0 || y >= GRID_SIZE || board[x][y] !== 0 || gameOver) {
                console.log("无效的落子位置:", x, y, "或游戏已结束:", gameOver);
                return;
            }
            
            console.log("放置棋子:", x, y, "玩家:", currentPlayer);
            
            // 更新棋盘
            board[x][y] = currentPlayer;
            
            // 播放落子音效
            moveSound.currentTime = 0;
            moveSound.play().catch(e => console.log("音频播放失败:", e));
            
            // 添加落子记录
            const moveNumber = moveHistory.length + 1;
            const notation = String.fromCharCode(65 + x) + (y + 1);
            moveHistory.push({ x, y, player: currentPlayer, notation, moveNumber });
            
            // 更新历史记录显示
            updateMoveHistory();
            
            // 添加落子动画
            addPlacementAnimation(x, y, currentPlayer);
            
            // 产生粒子效果
            generateParticles(x * CELL_SIZE + CELL_SIZE/2, y * CELL_SIZE + CELL_SIZE/2, currentPlayer);
            
            // 检查胜负
            if (checkWin(x, y, currentPlayer)) {
                setTimeout(() => {
                    gameInfo.textContent = currentPlayer === 1 ? '黑棋获胜！' : '白棋获胜！';
                    gameOverMessage.textContent = currentPlayer === 1 ? '黑棋获胜！' : '白棋获胜！';
                    gameOverDialog.style.display = 'block';
                    gameOver = true;
                    
                    // 播放胜利音效
                    winSound.currentTime = 0;
                    winSound.play().catch(e => console.log("音频播放失败:", e));
                    
                    // 胜利特效
                    createVictoryEffect(x, y);
                }, 500); // 延迟显示胜利对话框，让动画先播放完
            } else if (checkDraw()) {
                setTimeout(() => {
                    gameInfo.textContent = '平局！';
                    gameOverMessage.textContent = '平局！';
                    gameOverDialog.style.display = 'block';
                    gameOver = true;
                }, 500);
            } else {
                // 切换玩家
                currentPlayer = (currentPlayer === 1) ? -1 : 1; // 确保正确切换
                gameInfo.textContent = currentPlayer === 1 ? '当前轮到黑棋' : '当前轮到白棋';
                console.log("切换到玩家:", currentPlayer);
            }
        }
        
        // 更新移动历史记录
        function updateMoveHistory() {
            const historyContainer = document.getElementById('moveHistory');
            moveList.innerHTML = '';
            
            if (moveHistory.length === 0) {
                historyContainer.style.display = 'none';
                return;
            }
            
            historyContainer.style.display = 'block';
            
            moveHistory.forEach(move => {
                const moveElement = document.createElement('div');
                moveElement.className = 'history-move';
                moveElement.textContent = `${move.moveNumber}. ${move.player === 1 ? '黑' : '白'} ${move.notation}`;
                moveList.appendChild(moveElement);
            });
            
            // 滚动到最新记录
            moveList.scrollTop = moveList.scrollHeight;
        }
        
        // 添加落子动画
        function addPlacementAnimation(x, y, player) {
            const centerX = x * CELL_SIZE + CELL_SIZE/2;
            const centerY = y * CELL_SIZE + CELL_SIZE/2;
            
            // 创建波纹效果
            for (let i = 0; i < 3; i++) {
                setTimeout(() => {
                    particles.push({
                        x: centerX,
                        y: centerY,
                        size: CELL_SIZE * 0.3 + i * CELL_SIZE * 0.15,
                        isRing: true,
                        color: player === 1 ? 'rgba(0, 0, 0, 0.6)' : 'rgba(255, 255, 255, 0.6)',
                        alpha: 0.7 - i * 0.2,
                        life: 25,
                        expand: true
                    });
                }, i * 100);
            }
            
            // 创建下落阴影效果
            const shadowCount = 5;
            for (let i = 0; i < shadowCount; i++) {
                setTimeout(() => {
                    const progress = i / shadowCount;
                    const shadowY = centerY - CELL_SIZE * (1 - progress) * 0.8;
                    
                    particles.push({
                        x: centerX,
                        y: shadowY,
                        size: CELL_SIZE * 0.4 * (1 + progress * 0.2),
                        isShadow: true,
                        color: player === 1 ? 'rgba(0, 0, 0, 0.2)' : 'rgba(0, 0, 0, 0.1)',
                        alpha: 0.3 * progress,
                        life: 5
                    });
                }, i * 30);
            }
            
            // 创建弹跳效果
            const bounceSteps = 8;
            for (let i = 0; i < bounceSteps; i++) {
                setTimeout(() => {
                    const progress = i / bounceSteps;
                    const bounceHeight = Math.sin(progress * Math.PI) * CELL_SIZE * 0.1;
                    
                    particles.push({
                        x: centerX,
                        y: centerY - bounceHeight,
                        size: CELL_SIZE * 0.4,
                        isBounce: true,
                        color: player === 1 ? '#000' : '#fff',
                        alpha: 0.3,
                        life: 5
                    });
                }, 300 + i * 40);
            }
        }
        
        // 开始游戏
        function startGame() {
            if (!gameRunning) {
                gameRunning = true;
                
                // 清除之前的定时器（如果有）
                if (gameInterval) {
                    clearInterval(gameInterval);
                }
                
                // 启动游戏循环
                gameInterval = setInterval(gameLoop, gameSpeed);
                
                // 启动动画循环
                startGameLoop();
                
                // 更新按钮状态
                document.getElementById('startBtn').disabled = true;
                document.getElementById('pauseBtn').disabled = false;
            }
        }
        
        // 暂停游戏
        function pauseGame() {
            if (gameRunning) {
                gameRunning = false;
                clearInterval(gameInterval);
                gameInterval = null;
                
                // 更新按钮状态
                document.getElementById('startBtn').disabled = false;
                document.getElementById('startBtn').textContent = '继续游戏';
                document.getElementById('pauseBtn').disabled = true;
            }
        }
        
        // 重新开始游戏
        function restartGame() {
            resetGame();
            
            // 更新按钮状态
            document.getElementById('startBtn').disabled = false;
            document.getElementById('startBtn').textContent = '开始游戏';
            document.getElementById('pauseBtn').disabled = true;
            
            // 重绘游戏
            drawGame();
        }
        
        // 游戏主循环
        function gameLoop() {
            if (!gameRunning) return;
            
            // 更新蛇的方向
            direction = nextDirection;
            
            // 移动蛇
            moveSnake();
            
            // 检查碰撞
            if (checkCollision()) {
                gameOver();
                return;
            }
            
            // 检查是否吃到食物
            checkFood();
        }
        
        // 移动蛇
        function moveSnake() {
            // 获取蛇头的当前位置
            const head = {...snake[0]};
            
            // 根据当前方向移动蛇头
            switch (direction) {
                case 'up':
                    head.y--;
                    break;
                case 'down':
                    head.y++;
                    break;
                case 'left':
                    head.x--;
                    break;
                case 'right':
                    head.x++;
                    break;
            }
            
            // 将新的头部添加到蛇身前面
            snake.unshift(head);
            
            // 如果没有吃到食物，移除尾部；否则在 checkFood() 中处理
            if (!food || head.x !== food.x || head.y !== food.y) {
                snake.pop();
            }
        }
        
        // 检查碰撞
        function checkCollision() {
            const head = snake[0];
            
            // 检查是否撞墙
            if (
                head.x < 0 || 
                head.x >= GRID_SIZE || 
                head.y < 0 || 
                head.y >= GRID_SIZE
            ) {
                return true;
            }
            
            // 检查是否撞到自己（从第二个身体部分开始检查）
            for (let i = 1; i < snake.length; i++) {
                if (head.x === snake[i].x && head.y === snake[i].y) {
                    return true;
                }
            }
            
            // 没有碰撞
            return false;
        }
        
        // 检查是否吃到食物
        function checkFood() {
            const head = snake[0];
            
            // 如果蛇头碰到食物
            if (food && head.x === food.x && head.y === food.y) {
                // 增加分数
                score += 10;
                updateScore();
                
                // 增加游戏速度
                if (gameSpeed > 50) {
                    gameSpeed -= 2;
                    clearInterval(gameInterval);
                    gameInterval = setInterval(gameLoop, gameSpeed);
                }
                
                // 生成新的食物
                generateFood();
                
                // 创建吃食物效果
                createFoodParticles(head.x, head.y);
                
                // 注意：蛇身增长已在 moveSnake() 中处理
            }
        }
        
        // 生成食物
        function generateFood() {
            // 创建一个可用位置的列表（排除蛇身占据的位置）
            const availablePositions = [];
            
            for (let x = 0; x < GRID_SIZE; x++) {
                for (let y = 0; y < GRID_SIZE; y++) {
                    // 检查当前位置是否被蛇占据
                    let isOccupied = false;
                    for (const segment of snake) {
                        if (segment.x === x && segment.y === y) {
                            isOccupied = true;
                            break;
                        }
                    }
                    
                    // 如果未被占据，则添加到可用位置
                    if (!isOccupied) {
                        availablePositions.push({x, y});
                    }
                }
            }
            
            // 如果有可用位置，随机选择一个作为食物位置
            if (availablePositions.length > 0) {
                const randomIndex = Math.floor(Math.random() * availablePositions.length);
                food = availablePositions[randomIndex];
            } else {
                // 如果没有可用位置（玩家赢了！）
                food = null;
                gameOver(true);
            }
        }
        
        // 游戏结束
        function gameOver(win = false) {
            gameRunning = false;
            clearInterval(gameInterval);
            gameInterval = null;
            
            // 更新按钮状态
            document.getElementById('startBtn').disabled = true;
            document.getElementById('pauseBtn').disabled = true;
            
            // 显示游戏结束消息
            const message = win ? 
                `恭喜！你赢了！得分: ${score}` : 
                `游戏结束！得分: ${score}`;
            
            document.getElementById('status').textContent = message;
            
            // 爆炸效果
            if (!win) {
                createExplosionEffect(snake[0].x, snake[0].y);
            } else {
                // 胜利特效
                createVictoryEffect();
            }
        }
        
        // 更新分数显示
        function updateScore() {
            document.getElementById('score').textContent = score;
        }
        
        // 初始化游戏
        window.addEventListener('DOMContentLoaded', init);

        // 添加触摸控制
        function addTouchControls() {
            // 上一次触摸的位置
            let touchStartX = 0;
            let touchStartY = 0;
            
            // 触摸开始
            canvas.addEventListener('touchstart', function(event) {
                touchStartX = event.touches[0].clientX;
                touchStartY = event.touches[0].clientY;
                event.preventDefault();
            }, false);
            
            // 触摸结束
            canvas.addEventListener('touchend', function(event) {
                const touchEndX = event.changedTouches[0].clientX;
                const touchEndY = event.changedTouches[0].clientY;
                
                // 计算滑动距离
                const dx = touchEndX - touchStartX;
                const dy = touchEndY - touchStartY;
                
                // 如果水平滑动距离大于垂直滑动距离
                if (Math.abs(dx) > Math.abs(dy)) {
                    // 水平滑动
                    if (dx > 0 && direction !== 'left') {
                        nextDirection = 'right';
                    } else if (dx < 0 && direction !== 'right') {
                        nextDirection = 'left';
                    }
                } else {
                    // 垂直滑动
                    if (dy > 0 && direction !== 'up') {
                        nextDirection = 'down';
                    } else if (dy < 0 && direction !== 'down') {
                        nextDirection = 'up';
                    }
                }
                
                // 如果游戏未运行，自动开始
                if (!gameRunning) {
                    startGame();
                }
                
                event.preventDefault();
            }, false);
        }

        // 根据窗口大小调整画布
        function resizeCanvas() {
            // 获取容器宽度
            const container = document.querySelector('.game-area');
            const containerWidth = container.clientWidth;
            
            // 根据容器宽度确定棋盘大小，但不超过最大尺寸
            BOARD_SIZE = Math.min(containerWidth - 20, 500);
            CELL_SIZE = BOARD_SIZE / GRID_SIZE;
            
            // 设置画布大小
            canvas.width = BOARD_SIZE;
            canvas.height = BOARD_SIZE;
            
            // 重绘游戏
            drawGame();
        }

        // 动画循环
        let animationFrameId;
        function startGameLoop() {
            // 取消之前的动画帧
            if (animationFrameId) {
                cancelAnimationFrame(animationFrameId);
            }
            
            // 游戏动画循环
            function loop() {
                drawGame();
                
                // 更新并绘制粒子效果
                updateParticles();
                
                // 如果游戏仍在运行，继续循环
                if (gameRunning) {
                    animationFrameId = requestAnimationFrame(loop);
                }
            }
            
            // 开始循环
            animationFrameId = requestAnimationFrame(loop);
        }

        // 绘制游戏
        function drawGame() {
            // 清除画布
            ctx.clearRect(0, 0, canvas.width, canvas.height);
            
            // 绘制背景和网格
            drawBoard();
            
            // 绘制食物
            if (food) {
                drawFood();
            }
            
            // 绘制蛇
            drawSnake();
            
            // 绘制粒子效果
            drawParticles();
            
            // 如果游戏结束，绘制覆盖层
            if (!gameRunning && snake.length > 0) {
                drawGameOverOverlay();
            }
        }

        // 绘制蛇
        function drawSnake() {
            // 绘制蛇身
            for (let i = snake.length - 1; i >= 0; i--) {
                const segment = snake[i];
                const x = segment.x * CELL_SIZE;
                const y = segment.y * CELL_SIZE;
                
                // 判断是头部还是身体
                const isHead = i === 0;
                
                // 设置填充颜色（头部和身体颜色不同）
                ctx.fillStyle = isHead ? colors.snake.head : colors.snake.body;
                
                // 绘制圆角矩形
                drawRoundedRect(
                    x + 1, 
                    y + 1, 
                    CELL_SIZE - 2, 
                    CELL_SIZE - 2, 
                    CELL_SIZE / 4
                );
                
                // 绘制轮廓
                ctx.strokeStyle = colors.snake.outline;
                ctx.lineWidth = 1;
                ctx.stroke();
                
                // 如果是头部，添加眼睛
                if (isHead) {
                    drawSnakeEyes(segment);
                }
            }
        }

        // 绘制蛇眼睛
        function drawSnakeEyes(head) {
            const x = head.x * CELL_SIZE;
            const y = head.y * CELL_SIZE;
            const eyeSize = CELL_SIZE / 6;
            const eyeOffset = CELL_SIZE / 3;
            
            // 眼睛位置基于当前方向
            let leftEyeX, leftEyeY, rightEyeX, rightEyeY;
            
            switch(direction) {
                case 'up':
                    leftEyeX = x + eyeOffset;
                    leftEyeY = y + eyeOffset;
                    rightEyeX = x + CELL_SIZE - eyeOffset - eyeSize;
                    rightEyeY = y + eyeOffset;
                    break;
                case 'down':
                    leftEyeX = x + eyeOffset;
                    leftEyeY = y + CELL_SIZE - eyeOffset - eyeSize;
                    rightEyeX = x + CELL_SIZE - eyeOffset - eyeSize;
                    rightEyeY = y + CELL_SIZE - eyeOffset - eyeSize;
                    break;
                case 'left':
                    leftEyeX = x + eyeOffset;
                    leftEyeY = y + eyeOffset;
                    rightEyeX = x + eyeOffset;
                    rightEyeY = y + CELL_SIZE - eyeOffset - eyeSize;
                    break;
                case 'right':
                    leftEyeX = x + CELL_SIZE - eyeOffset - eyeSize;
                    leftEyeY = y + eyeOffset;
                    rightEyeX = x + CELL_SIZE - eyeOffset - eyeSize;
                    rightEyeY = y + CELL_SIZE - eyeOffset - eyeSize;
                    break;
            }
            
            // 绘制眼睛
            ctx.fillStyle = 'white';
            ctx.fillRect(leftEyeX, leftEyeY, eyeSize, eyeSize);
            ctx.fillRect(rightEyeX, rightEyeY, eyeSize, eyeSize);
            
            // 眼球
            ctx.fillStyle = 'black';
            ctx.fillRect(leftEyeX + eyeSize/4, leftEyeY + eyeSize/4, eyeSize/2, eyeSize/2);
            ctx.fillRect(rightEyeX + eyeSize/4, rightEyeY + eyeSize/4, eyeSize/2, eyeSize/2);
        }

        // 绘制圆角矩形
        function drawRoundedRect(x, y, width, height, radius) {
            ctx.beginPath();
            ctx.moveTo(x + radius, y);
            ctx.lineTo(x + width - radius, y);
            ctx.quadraticCurveTo(x + width, y, x + width, y + radius);
            ctx.lineTo(x + width, y + height - radius);
            ctx.quadraticCurveTo(x + width, y + height, x + width - radius, y + height);
            ctx.lineTo(x + radius, y + height);
            ctx.quadraticCurveTo(x, y + height, x, y + height - radius);
            ctx.lineTo(x, y + radius);
            ctx.quadraticCurveTo(x, y, x + radius, y);
            ctx.closePath();
            ctx.fill();
        }

        // 绘制食物
        function drawFood() {
            const x = food.x * CELL_SIZE;
            const y = food.y * CELL_SIZE;
            
            // 绘制苹果形状
            ctx.fillStyle = colors.food;
            ctx.beginPath();
            ctx.arc(x + CELL_SIZE/2, y + CELL_SIZE/2, CELL_SIZE/2 - 2, 0, Math.PI * 2);
            ctx.fill();
            
            // 添加高光
            ctx.fillStyle = 'rgba(255, 255, 255, 0.5)';
            ctx.beginPath();
            ctx.arc(x + CELL_SIZE/3, y + CELL_SIZE/3, CELL_SIZE/6, 0, Math.PI * 2);
            ctx.fill();
            
            // 绘制苹果茎
            ctx.fillStyle = 'green';
            ctx.fillRect(x + CELL_SIZE/2 - 1, y + 2, 2, 4);
        }

        // 绘制游戏结束覆盖层
        function drawGameOverOverlay() {
            ctx.fillStyle = colors.gameOver;
            ctx.fillRect(0, 0, BOARD_SIZE, BOARD_SIZE);
        }

        // 粒子系统
        // 创建食物被吃掉的粒子效果
        function createFoodParticles(x, y) {
            const count = 10;
            const cellX = x * CELL_SIZE;
            const cellY = y * CELL_SIZE;
            
            for (let i = 0; i < count; i++) {
                particles.push({
                    x: cellX + CELL_SIZE / 2,
                    y: cellY + CELL_SIZE / 2,
                    size: Math.random() * 3 + 2,
                    speedX: (Math.random() - 0.5) * 6,
                    speedY: (Math.random() - 0.5) * 6,
                    color: colors.food,
                    alpha: 1,
                    life: 1
                });
            }
        }

        // 创建爆炸效果
        function createExplosionEffect(x, y) {
            const count = 30;
            const cellX = x * CELL_SIZE;
            const cellY = y * CELL_SIZE;
            
            for (let i = 0; i < count; i++) {
                particles.push({
                    x: cellX + CELL_SIZE / 2,
                    y: cellY + CELL_SIZE / 2,
                    size: Math.random() * 5 + 3,
                    speedX: (Math.random() - 0.5) * 10,
                    speedY: (Math.random() - 0.5) * 10,
                    color: i % 2 === 0 ? colors.snake.head : colors.snake.body,
                    alpha: 1,
                    life: 1
                });
            }
        }

        // 创建胜利效果
        function createVictoryEffect() {
            const count = 100;
            
            for (let i = 0; i < count; i++) {
                particles.push({
                    x: Math.random() * BOARD_SIZE,
                    y: Math.random() * BOARD_SIZE,
                    size: Math.random() * 5 + 3,
                    speedX: (Math.random() - 0.5) * 3,
                    speedY: -Math.random() * 5 - 2,
                    color: `hsl(${Math.random() * 360}, 100%, 50%)`,
                    alpha: 1,
                    life: 1
                });
            }
        }

        // 更新粒子状态
        function updateParticles() {
            for (let i = particles.length - 1; i >= 0; i--) {
                const p = particles[i];
                
                // 更新位置
                p.x += p.speedX;
                p.y += p.speedY;
                
                // 减少生命值
                p.life -= 0.02;
                p.alpha = p.life;
                
                // 如果粒子寿命结束，从数组中移除
                if (p.life <= 0) {
                    particles.splice(i, 1);
                }
            }
        }

        // 绘制粒子
        function drawParticles() {
            for (const p of particles) {
                ctx.globalAlpha = p.alpha;
                ctx.fillStyle = p.color;
                ctx.beginPath();
                ctx.arc(p.x, p.y, p.size, 0, Math.PI * 2);
                ctx.fill();
            }
            
            // 重置透明度
            ctx.globalAlpha = 1;
        }

        // 撤销上一步（可选功能）
        function undoMove() {
            // 仅在游戏运行状态下才能撤销
            if (gameRunning && snake.length > 3) {
                // 移除蛇尾并将其添加到头部
                const tail = snake.pop();
                snake.unshift(tail);
                
                // 根据新头部位置调整方向
                const head = snake[0];
                const neck = snake[1];
                
                if (head.x < neck.x) direction = nextDirection = 'left';
                else if (head.x > neck.x) direction = nextDirection = 'right';
                else if (head.y < neck.y) direction = nextDirection = 'up';
                else if (head.y > neck.y) direction = nextDirection = 'down';
                
                // 重绘游戏
                drawGame();
            }
        }

        // 加载游戏
        window.onload = init;
    </script>
</body>
</html>